package luj.groovy.excel.internal.table.header


import luj.groovy.excel.api.table.header.Header
import luj.groovy.excel.internal.table.create.BuildHeaderImpl
import org.apache.poi.ss.usermodel.Sheet

import java.util.stream.Collectors

class TableHeaderMaker {

  interface Result {

    Header header()

    int lastRow()

    int firstColumn()

    int lastColumn()
  }

  TableHeaderMaker(BuildHeaderImpl builder) {
    _builder = builder
  }

  Result make() {
    Sheet sheet = _builder._sheet
    int startRow = _builder._startRow
    int endRow = startRow + _builder._rowSize

    List mergeList = sheet.mergedRegions.stream()
        .filter { it.firstRow >= startRow }
        .filter { it.lastRow < endRow }
        .filter { it.firstColumn < it.lastColumn }
        .collect(Collectors.toList())

    List fieldList = new HeaderFieldFinder(sheet, startRow, endRow, mergeList).findFields()
    int firstCol = getFirstColumn(fieldList)
    int lastCol = getLastColumn(fieldList)

    def header = new HeaderImpl()
    header._fieldList = fieldList.stream()
        .map { it.field() }
        .filter { it._parent == null }
        .collect()

    return new Result() {
      @Override
      Header header() {
        return header
      }

      @Override
      int lastRow() {
        return endRow - 1
      }

      @Override
      int firstColumn() {
        return firstCol
      }

      @Override
      int lastColumn() {
        return lastCol
      }
    }
  }

  private int getFirstColumn(List<HeaderFieldFinder.Result> fieldList) {
    return fieldList.stream()
        .mapToInt { it.firstColumn() }
        .min()
        .orElse(0)
  }

  private int getLastColumn(List<HeaderFieldFinder.Result> fieldList) {
    return fieldList.stream()
        .mapToInt { it.lastColumn() }
        .max()
        .orElse(0)
  }

  private final BuildHeaderImpl _builder
}
